﻿using Architecture.CrossCutting.Tracing.Models;
using Microsoft.Diagnostics.Tracing;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Architecture.CrossCutting.Web.Tracing.ETW
{
    public class ETWIISLogParser
    {

        public static ETWIISLogParser Current = new ETWIISLogParser();


        public IISLog CreateFromTraceEvent(TraceEvent data)
        {

            return new IISLog()
            {

                RequestId = Guid.NewGuid(),
                //    data.PayloadByName("EnabledFieldsFlags")
                RequestDate = AutoParser<DateTime>.Parse(data.PayloadByName("date")),
                //data.PayloadByName("time")
                ClientIp = AutoParser<String>.Parse(data.PayloadByName("cip")),
                ClientUserName = AutoParser<String>.Parse(data.PayloadByName("csusername")),
                SiteName = AutoParser<String>.Parse(data.PayloadByName("ssitename")),
                //data.PayloadByName("scomputername"),
                ServerIp = AutoParser<String>.Parse(data.PayloadByName("sip")),
                ClientMethod = AutoParser<String>.Parse(data.PayloadByName("csmethod")),
                ClientUri = AutoParser<String>.Parse(data.PayloadByName("csuristem")),
                ClientQuery = AutoParser<String>.Parse(data.PayloadByName("csuriquery")),
                ResponseStatus = AutoParser<int>.Parse(data.PayloadByName("scstatus")),
                ResponseWin32Status = AutoParser<String>.Parse(data.PayloadByName("scwin32status")),
                ResponseSize = AutoParser<long>.Parse(data.PayloadByName("scbytes")),
                RequestSize = AutoParser<long>.Parse(data.PayloadByName("csbytes")),
                Duration = AutoParser<int>.Parse(data.PayloadByName("timetaken")),
                ServerPort = AutoParser<String>.Parse(data.PayloadByName("sport")),
                ClientAgent = AutoParser<String>.Parse(data.PayloadByName("csUserAgent")),
                // data.PayloadByName( "csCookie"
                //data.PayloadByName( "csReferer"
                ClientVersion = AutoParser<String>.Parse(data.PayloadByName("csversion")),
                // data.PayloadByName( "cshost"
                ResponseSubStatus = AutoParser<int>.Parse(data.PayloadByName("scsubstatus"))
                // data.PayloadByName("CustomFields"
            };


        }


    }


    public class AutoParser<T>
    {
        public static T Parse(Object value)
        {
            if (value == null) { return default(T); }
            else { return (T)System.Convert.ChangeType(value, typeof(T)); }
        }

    }

}
